package com.baoxin.chenxixc4coach;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.baoxin.chenxixc4coach.dialog.LoadingDialog;
import com.baoxin.chenxixc4coach.dialog.SelectPicDialog;
import com.baoxin.chenxixc4coach.java.MyHandler;
import com.baoxin.chenxixc4coach.java.SimpleResultHelper;
import com.baoxin.chenxixc4coach.utils.Interfaces;
import com.baoxin.chenxixc4coach.utils.MyToast;
import com.baoxin.chenxixc4coach.utils.NetUtil;
import com.baoxin.chenxixc4coach.utils.PicZipUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class IdentifyActivity extends BaseActivity implements SelectPicDialog.Identiface {

    private final int ALBUM_REQUEST_CODE = 1;
    private final int CAMERA_REQUEST_CODE = 2;
    private Bitmap[] bitmaps = new Bitmap[5];
    private String[] paths = new String[5];
    private ArrayList<ImageView> imgs = new ArrayList<>(5);
    private Handler handler;
    private int[] tag = new int[]{0, 0, 0, 0, 0};//图显示在ImageView上？
    private boolean[] uploadTag = new boolean[]{false, false, false, false, false};//图上传成功了？
    private Button mSubmit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_identify);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mSubmit = findViewById(R.id.submit);

        handler = new MyHandler(this, activity) {
            @Override
            public void handleMessage(Message msg) {
                Bitmap bitmap = (Bitmap) msg.obj;
                switch (msg.what) {
                    case 0:
                        imgs.get(0).setImageBitmap(bitmap);
                        tag[0] = 1;
                        break;
                    case 1:
                        imgs.get(1).setImageBitmap(bitmap);
                        tag[1] = 1;
                        break;
                    case 2:
                        imgs.get(2).setImageBitmap(bitmap);
                        tag[2] = 1;
                        break;
                    case 3:
                        imgs.get(3).setImageBitmap(bitmap);
                        tag[3] = 1;
                        break;
                    case 4:
                        imgs.get(4).setImageBitmap(bitmap);
                        tag[4] = 1;
                        break;
                    case 100:
                        uploadTag[100 - 100] = true;
                        uploadComplete();
                        break;
                    case 101:
                        uploadTag[101 - 100] = true;
                        uploadComplete();
                        break;
                    case 102:
                        uploadTag[102 - 100] = true;
                        uploadComplete();
                        break;
                    case 103:
                        uploadTag[103 - 100] = true;
                        uploadComplete();
                        break;
                    case 104:
                        uploadTag[104 - 100] = true;
                        uploadComplete();
                        break;
                }
                updateSubmitable();

            }
        };

        imgs.add((ImageView) findViewById(R.id.img1));
        imgs.add((ImageView) findViewById(R.id.img2));
        imgs.add((ImageView) findViewById(R.id.img3));
        imgs.add((ImageView) findViewById(R.id.img4));
        imgs.add((ImageView) findViewById(R.id.img5));
    }

    int selected;

    /**
     * 加载到imageview上
     *
     * @param view
     */
    public void onUpload(View view) {
        switch (view.getId()) {
            case R.id.bt1:
                selected = 0;
                break;
            case R.id.bt2:
                selected = 1;
                break;
            case R.id.bt3:
                selected = 2;
                break;
            case R.id.bt4:
                selected = 3;
                break;
            case R.id.bt5:
                selected = 4;
                break;
        }
        SelectPicDialog selectPicDialog = new SelectPicDialog();
        //    selectPicDialog.setStyle(DialogFragment.STYLE_NO_FRAME, 0);//不设边框，真正的match_width
        selectPicDialog.setIdentifaceImpl(this);
        selectPicDialog.show(getSupportFragmentManager(), "");

    }

    @Override
    public void fromCamera() {
        checkPermission(new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE});
    }

    @Override
    public void fromAlbum() {
        checkPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE});
    }


    private void checkPermission(String[] permissions) {
        if (Build.VERSION.SDK_INT >= 23) {//6.0及以上

            boolean allGet = true;//默认权限都有

            for (String permission : permissions) {
                allGet = allGet && (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED);
            }
            if (allGet) {//权限都有
                if (permissions[0].equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    openAlbum();
                } else if (permissions[0].equals(Manifest.permission.CAMERA)) {
                    openCamera();
                }
            } else {//不都有
                requestPermissions(permissions, 1);
            }


        } else {//6.0以下，直接使用
            if (permissions[0].equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                openAlbum();
            } else if (permissions[0].equals(Manifest.permission.CAMERA)) {
                openCamera();
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (permissions[0].equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                MyToast.show(this, "打开相册");
                openAlbum();
            } else if (permissions[0].equals(Manifest.permission.CAMERA)) {
                MyToast.show(this, "打开相机");
                openCamera();
            }

        } else {
            showMissingPermissionDialog();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        //选择图片后返回
        if (requestCode == ALBUM_REQUEST_CODE) {
            if (data == null)
                return;
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String localPicPath = cursor.getString(columnIndex);
            cursor.close();

            addPic(localPicPath);
        } else if (requestCode == CAMERA_REQUEST_CODE) {//拍照后返回
            int a = resultCode;
            if (resultCode == 0) return;//resultCode=0代表没有拍照返回，-1代表拍照了返回
            addPic(photo.getPath());
            // imgs.get(selected).setImageURI(contentUri);
        }

    }

    private void openAlbum() {
        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, ALBUM_REQUEST_CODE);
    }

    File photo;

    private void openCamera() {
        Uri contentUri;
        photo = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/indentify/" + selected + ".png");
        photo.getParentFile().mkdirs();


        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//大于等于7.0
            contentUri = FileProvider.getUriForFile(this, "com.baoxin.chenxixc4coach.fileprovider", photo);
        } else {
            contentUri = Uri.fromFile(photo);
        }
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        startActivityForResult(intent, CAMERA_REQUEST_CODE);
    }

    private void addPic(final String path) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                Bitmap bitmap = PicZipUtil.compressImage(path);
                bitmaps[selected] = bitmap;
                paths[selected] = path;
                Message message = Message.obtain();
                message.obj = bitmap;
                message.what = selected;
                handler.sendMessage(message);

            }
        };
        thread.start();
    }

    private void updateSubmitable() {
        int sum = 0;
        for (int o : tag) {
            sum = sum + o;
        }
        if (sum == 5) {
            mSubmit.setEnabled(true);
        } else {
            mSubmit.setEnabled(false);
        }
    }

    LoadingDialog loadingDialog;

    public void onSubmit(View view) {

        LoadingDialog.Builder builder = new LoadingDialog.Builder(this);
        builder.setCancelable(true);
        builder.setMessage("上传中...");
        builder.setShowMessage(false);
        loadingDialog = builder.create();
        loadingDialog.show();

        for (int i = 0; i < paths.length; i++) {
            upload(paths[i], i);
        }
    }

    private void upload(final String localPicPath, final int index) {

        final String netPicPath = "identify/" + Math.random();
        PutObjectRequest put = new PutObjectRequest("bxpeter", netPicPath, localPicPath);

        MyApplication.oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                Log.d("ETag", result.getETag());
                Log.d("RequestId", result.getRequestId());
                handler.sendEmptyMessage(index + 100);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });

    }

    private void uploadComplete() {

        if (uploadTag[0] && uploadTag[1] && uploadTag[3] && uploadTag[4]) {//代表都上传到oos成功
            JSONObject body = new JSONObject();
            try {
                body.put("p1", paths[0]);
                body.put("p2", paths[1]);
                body.put("p3", paths[2]);
                body.put("p4", paths[3]);
                body.put("p5", paths[4]);
                NetUtil.post(activity, Interfaces.URL_IDENTIFY_LIST, body.toString(), new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        if (SimpleResultHelper.isSucceed(result)) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    loadingDialog.dismiss();
                                    Toast.makeText(activity, "上传成功！", Toast.LENGTH_SHORT).show();
                                    finish();
                                }
                            });
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    loadingDialog.dismiss();
                                    Toast.makeText(activity, "上传失败！", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
